package Test;

import java.util.ArrayList;

public class 顺时针打印数组 {
    public static ArrayList<Integer> printMatrix(int [][] matrix) {
        ArrayList<Integer> res=new ArrayList<>();
        int left=0;
        int right=matrix.length-1;
        int up=0;
        int down=matrix[0].length-1;
        while (true){
            for(int i=left;i<=right;i++){
                res.add(matrix[up][i]);
            }
            up++;
            if(up>down) break;
            for(int i=up;i<=down;i++){
                res.add(matrix[i][right]);
            }
            right--;
            if(right<left) break;
            for (int i=right;i>=left;i--){
                res.add(matrix[down][i]);
            }
            down--;
            if(down<up) break;;
            for (int i=down;i>=up;i--){
                res.add(matrix[i][left  ]);
            }
            left++;
            if(left>right) break;
        }
        return res;
    }

    public static void main(String[] args) {
        int[][] nums={{1,2,3},{8,9,4},{7,6,5}};
        ArrayList<Integer> arrayList=printMatrix(nums);
        for (int i:arrayList){
            System.out.println(i);
        }
    }
}
